package com.tianji.learning.utils;

import lombok.Data;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Data
public class DelayTask<T> implements Delayed {
  //延时
  private Long delayNanos;
  // 执行数据
  private T data;

  public DelayTask(T data,Duration duration) {
    this.data = data;
    this.delayNanos = System.nanoTime() + duration.toNanos();
  }

  @Override
  public long getDelay(TimeUnit unit) {
    return unit.convert(Math.max(0, delayNanos - System.nanoTime()), TimeUnit.NANOSECONDS);
  }

  @Override
  public int compareTo(Delayed o) {
    long diff = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
    if (diff > 0) {
      return 1;
    } else if (diff < 0) {
      return -1;
    }
    return 0;
  }
}
